﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using AUV5.Common;
namespace AUV5.Web.Pages
{
    public partial class ServiceEdit : PageBaseFrontend
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hfAuth.Value = Session.SessionID;
                hfAspSessID.Value = Session.SessionID;
                if (base.IsVerified)
                {
                    if (VerifiedInfo.User.State == (int)Common.Enum.auvState.Disable)
                    {
                        base.ErrorInfo = "您的帐户尚未激活，不能发布信息!";
                        Response.Redirect(Request.UrlReferrer.ToString());
                    }
                    bindCategory();

                    //最热关键字
                    bindHotKey();

                    //时间格式为1111-11-1，方便使用JS截取年月日，生成保存上传文件的目录
                    hfadddate.Value = DateTime.Now.ToString("yyyy-MM-dd");

                    if (!string.IsNullOrEmpty(Request["title"]))
                    {
                        this.txtTitle.Text = Request["title"];
                    }

                    if (Request["serviceID"] != null)
                    {
                        initService();
                    }

                }
                else
                {
                    Response.Redirect(URL_INDEX);
                }
            }
        }

        //绑定热门关键字
        private void bindHotKey()
        {
            repHotKey.DataSource = BLL.KeywordBLL.Instance.GetHotestKey();
            repHotKey.DataBind();
        }
        //初始化要修改的服务
        private void initService()
        {
            string serviceID = Request["serviceID"];
            Model.ServiceInfo service = BLL.ServiceInfoBLL.Instance.GetDetail(serviceID);
            txtTitle.Text = service.Title.HTMLDeCode();
            ddlCategory.SelectedValue = service.CategoryID;
            ddlPrice.SelectedValue = service.Price.ToString("0");
            txtDescription.Text = service.Description.HTMLDeCode();
            //txtInstruction.Text = service.Instruction;
            txtTags.Text = BLL.ServiceInfoBLL.Instance.GetTagList(service.ServiceID).HTMLDeCode();
            hfpath.Value = BLL.ServiceAttachmentBLL.Instance.GetImgPathList(service.ServiceID);
            ddlDuration.SelectedValue = service.Duration.ToString();

            //限时
            if (service.EndDate > DateTime.Now)
            {

                if (service.EndDate.Year != DateTime.MaxValue.Year)
                {
                    ckbTimeLimited.Checked = true;
                    txtLastTime.Text = (service.EndDate - DateTime.Now).Days.ToString();
                }
            }

            //限量
            cbNeedStock.Checked = service.NeedStock;
            if (service.NeedStock)
            {
                txtStock.Text = service.Stock.ToString();
            }


            chkNeedShipping.Checked = service.Shippable;
            txtNativeCharge.Text = service.NativeShipCharge.ToString("0.00");
            //txtOtherCharge.Text = service.OtherShipCharge.ToString("0.00");
            //时间格式为1111-11-1，方便使用JS截取年月日
            hfadddate.Value = service.CreateDate.ToString("yyyy-MM-dd");

            //视频
            Model.ServiceAttachment video = BLL.ServiceAttachmentBLL.Instance.GetVideo(serviceID);
            if (video != null)
            {
                videoUpload.Visible = false;
                videoManage.Visible = true;
                imgVideo.ImageUrl = video.ImagePath;
            }
            else
            {
                videoUpload.Visible = true;
                videoManage.Visible = false;
            }
        }

        //绑定服务信息类别
        private void bindCategory()
        {
            ddlCategory.DataSource = BLL.ServiceCategoryBLL.Instance.GetActiveList();
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataValueField = "CategoryID";
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0, new ListItem("==请选择服务类别==", "0"));
        }

        //提交信息（添加或修改）
        protected void submit_Click(object sender, EventArgs e)
        {
            if (base.IsVerified)
            {
                if (VerifiedInfo.User.State != (int)Common.Enum.auvState.Disable)
                {
                    string Title = "";
                    string CategoryID = "";
                    string Description = "";
                    string Instruction = "";
                    string[] keywords = null;
                    bool Shippable = false;
                    int Duration = 1;
                    decimal shipCharge = 0;
                    //decimal NativeShipCharge = 0;
                    //decimal OtherShipCharge = 0;
                    //是否通过验证
                    bool pass = true;
                    //错误信息
                    StringBuilder error = new StringBuilder();
                    string li = "   {0}<br />";

                    #region   数据的服务器端验证 Vinlon 2011-11-1
                    if (txtTitle.Text.Trim() != "")
                    {
                        if (BadWordsFilter.Instance.HasBadWord(txtTitle.Text.Trim()))
                        {
                            error.AppendFormat(li, "标题中含有非法字符！");
                            pass = false;
                        }
                        else if (BLL.ServiceInfoBLL.Instance.TitleExists(txtTitle.Text.Trim(), Request["serviceid"]))
                        {
                            error.AppendFormat(li, "标题已存在！");
                            pass = false;
                        }
                        else
                        {
                            Title = txtTitle.Text.Trim();
                        }
                    }
                    else
                    {
                        error.AppendFormat(li, "标题不能为空！");
                        pass = false;
                    }

                    if (ddlCategory.SelectedIndex != 0)
                    {
                        CategoryID = ddlCategory.SelectedValue;
                    }
                    else
                    {
                        error.AppendFormat(li, "请选择服务类别！");
                        pass = false;
                    }
                    if (BadWordsFilter.Instance.HasBadWord(txtDescription.Text.Trim()))
                    {
                        error.AppendFormat(li, "描述中含有非法字符！");
                        pass = false;
                    }
                    else
                    {
                        Description = txtDescription.Text.Trim();
                    }

                    //每个关键字长度不能大于10
                    keywords = txtTags.Text.Trim().Replace('，', ',').Split(',');
                    foreach (var key in keywords)
                    {
                        if (key.Length > 10)
                        {
                            error.AppendFormat(li, "关键字长度不能大于10个字符（五个中文字符）！");
                            pass = false;
                        }
                    }
                    try
                    {
                        Duration = Convert.ToInt32(ddlDuration.SelectedValue);
                    }
                    catch
                    {
                        error.AppendFormat(li, "完成所需时间不能为空且必须为整数！");
                        pass = false;
                    }
                    Shippable = chkNeedShipping.Checked;
                    if (chkNeedShipping.Checked)
                    {
                        if (txtNativeCharge.Text.Trim() == "") // || txtOtherCharge.Text.Trim() == "")
                        {
                            error.AppendFormat(li, "运费不能为空！");
                            pass = false;
                        }
                    }
                    try
                    {
                        shipCharge = txtNativeCharge.Text.Trim() == "" ? 0 : decimal.Parse(txtNativeCharge.Text.Trim());
                        //OtherShipCharge = txtOtherCharge.Text.Trim() == "" ? 0 : decimal.Parse(txtOtherCharge.Text.Trim());
                    }
                    catch
                    {
                        error.AppendFormat(li, "运费必须为合法的数字！");
                        pass = false;
                    }

                    //已上传文件路径
                    List<string> imglist = null;
                    if (hfpath.Value == "")
                    {
                        error.AppendFormat(li, "至少上传一张图片！");
                        pass = false;
                    }
                    else
                    {
                        imglist = hfpath.Value.Split(',').ToList<string>();
                    }
                    #endregion
                    if (pass)
                    {
                        Model.ServiceInfo service = new Model.ServiceInfo();
                        if (Request["serviceID"] != null)
                        {
                            service = BLL.ServiceInfoBLL.Instance.GetDetail(Request["serviceID"].ToString());
                        }
                        //赋值
                        service.UserID = base.VerifiedInfo.User.UserID;
                        service.Price = decimal.Parse(ddlPrice.SelectedItem.Text);
                        service.Title = Title;
                        service.CategoryID = CategoryID;
                        service.Description = Description;
                        service.Instruction = Instruction;
                        service.Duration = Duration;
                        service.Shippable = Shippable;
                        service.NativeShipCharge = Shippable ? shipCharge : 0;
                        service.OtherShipCharge = Shippable ? shipCharge : 0;
                        //暂时存储的是IP地址
                        service.ServiceFrom = Request.UserHostAddress;

                        //限时
                        if (ckbTimeLimited.Checked)
                        {
                            service.EndDate = DateTime.Now.AddDays(int.Parse(txtLastTime.Text.Trim()));
                        }
                        else
                        {
                            service.EndDate = DateTime.MaxValue;
                        }

                        //限量
                        if (cbNeedStock.Checked)
                        {
                            service.NeedStock = true;
                            service.Stock = int.Parse(txtStock.Text.Trim());
                        }
                        else
                        {
                            service.NeedStock = false;
                            service.Stock = 0;
                        }
                        //判断
                        if (Request["serviceID"] == null)
                        {

                            service.ExtraFor = "";

                            //添加服务 
                            service.ServiceID = Guid.NewGuid().ToString();

                            BLL.ServiceInfoBLL.Instance.Add(service, keywords, imglist);
                        }

                        else
                        {
                            //修改
                            //service = BLL.ServiceInfoBLL.Instance.GetDetail(Request["serviceID"]);
                            service.UpdateDate = DateTime.Now;
                            BLL.ServiceInfoBLL.Instance.Update(service, keywords, imglist);
                        }


                        //判断是否有视频，有则添加到附件表中
                        if (!string.IsNullOrEmpty(hfvideopath.Value))
                        {
                            //视频路径是否有效
                            if (File.Exists(Server.MapPath(hfvideopath.Value)))
                            {
                                BLL.ServiceAttachmentBLL.Instance.AddVideo(service.ServiceID, hfvideopath.Value);
                            }
                        }
                        Response.Redirect("/Pages/ServiceManage.aspx");
                    }
                    else
                    {
                        lbMessage.InnerHtml = error.ToString();
                    }
                }
                else
                {
                    Alert("未通过审核的用户不可发布信息！");
                }
            }
            else
            {
                Response.Redirect("/Pages/Login.aspx");
            }
        }

        //删除视频
        protected void ibtnVideoDel_Click(object sender, ImageClickEventArgs e)
        {
            Model.ServiceAttachment video = BLL.ServiceAttachmentBLL.Instance.GetVideo(Request["serviceID"]);
            if (Request["serviceID"] != null)
            {
                string serviceID = Request["serviceID"].ToString();
                Model.ServiceAttachment att = BLL.ServiceAttachmentBLL.Instance.GetVideo(serviceID);
                if (att != null)
                {
                    BLL.ServiceAttachmentBLL.Instance.Delete(att);
                    //删除图片及缩略图
                    if (File.Exists(Server.MapPath(att.VideoPath)))
                    {
                        File.Delete(Server.MapPath(att.VideoPath));
                    }
                    if (File.Exists(Server.MapPath(att.ImagePath)))
                    {
                        File.Delete(Server.MapPath(att.ImagePath));
                    }
                    initService();
                }
            }
        }
    }
}